﻿@using Grand.Infrastructure
@model Payments.BrainTree.Models.PaymentInfoModel
@{
    Layout = "";
}
@inject IWorkContextAccessor _workContextAccessor

<style type="text/css">
    .braintree-input {
        height: 36px;
        border: 1px solid #ddd;
        padding: 8px;
        vertical-align: middle;
        color: #777;
    }

    .invalid-feedback {
        display: none;
        width: 100%;
        margin-top: .25rem;
        font-size: 80%;
        color: #dc3545;
    }
</style>

<div class="container">
    <div class="row align-items-center mb-3">
        <div class="col-md-4 col-12 text-md-right">
            <label class="col-form-label" asp-for="CardNumber">@Loc["Payment.CardNumber"]:</label>
        </div>
        <div class="col-md-4 col-12 text-right">
            <div class="braintree-input form-control" id="braintree-card-number"></div>
        </div>
    </div>

    <div class="row align-items-center mb-3">
        <div class="col-md-4 col-12 text-md-right">
            <label class="col-form-label" asp-for="ExpireMonth">@Loc["Payment.ExpirationDate"]:</label>
        </div>
        <div class="col-md-4 col-12 text-right d-md-flex input-group">
            <div class="braintree-input form-control col-md-6 col-12" id="braintree-expiration-date"></div>
        </div>
    </div>

    <div class="row align-items-center mb-3">
        <div class="col-md-4 col-12 text-md-right">
            <label class="col-form-label" asp-for="CardCode">@Loc["Payment.CardCode"]:</label>
        </div>
        <div class="col-md-4 col-12 text-right">
            <div class="braintree-input form-control" id="cc-cvv"></div>
            <input id="CardNonce" name="CardNonce" type="hidden"/>
        </div>
    </div>
</div>


<input type="hidden" asp-for="Errors"/>
<div style="color:red; margin:0 auto" id="braintree-errors"></div>
<div id="braintree-authentication"></div>
<div class="script-tag-info">
    @*
        Used when disable settings one page checkout
        <script asp-location="Footer">
    *@
    <script>
        var authorization = '@ViewBag.ClientToken';
        var submitForm = false;
        var stepBack = false;
        var components = {
            client: null,
            threeDSecure: null,
            hostedFields: null
        };
        var bankFrame = document.querySelector('#braintree-authentication');
        vmorder.validPayment = false;
        braintree.client.create({ authorization: authorization }, onClientCreate);
        function onClientCreate(err, client) {
            if (err) {
                //console.log('client error:', err);
                return;
            }
            components.client = client;
            braintree.hostedFields.create({
                client: client,
                fields: {
                    number: {
                        selector: '#braintree-card-number',
                        placeholder: '•••• •••• •••• ••••'
                    },
                    cvv: {
                        selector: '#cc-cvv',
                        placeholder: 'CVV'
                    },
                    expirationDate: {
                        selector: '#braintree-expiration-date',
                        placeholder: 'MM/YY'
                    }
                }
            }, onComponent('hostedFields'));
            braintree.threeDSecure.create({
                client: client,
                version: 2
            }, onComponent('threeDSecure'));
        }
        function onComponent(name) {
            return function (err, component) {
                if (err)
                    return;
                components[name] = component;
            }
        }
        function verifyCard(payload) {
            components.threeDSecure.verifyCard({
                bin: payload.details.bin,
                amount: '@ViewBag.OrderTotal',
                nonce: payload.nonce,
                challengeRequested: true,
                email: '@_workContextAccessor.WorkContext.CurrentCustomer.BillingAddress?.Email',
                billingAddress: {
                    givenName: '@_workContextAccessor.WorkContext.CurrentCustomer.BillingAddress?.FirstName',
                    surname: '@_workContextAccessor.WorkContext.CurrentCustomer.BillingAddress?.LastName',
                    phoneNumber: '@_workContextAccessor.WorkContext.CurrentCustomer.BillingAddress?.PhoneNumber',
                    streetAddress: '@_workContextAccessor.WorkContext.CurrentCustomer.BillingAddress?.Address1',
                    extendedAddress: '@_workContextAccessor.WorkContext.CurrentCustomer.BillingAddress?.Address2',
                    locality: '@_workContextAccessor.WorkContext.CurrentCustomer.BillingAddress?.City',
                    postalCode: '@_workContextAccessor.WorkContext.CurrentCustomer.BillingAddress?.ZipPostalCode',
                },
                onLookupComplete: function (data, next) {
                    // use `data` here, then call `next()`
                    next();
                    setTimeout(function () {
                        vmorder.vPaymentInfo.resetLoadWaiting();
                    }, 1000);
                }
            }, function (err, payload) {
                if (err) {
                    var currentErrorvalue = document.querySelector('#@Html.IdFor(model => model.Errors)').value;
                    document.querySelector('#@Html.IdFor(model => model.Errors)').value = currentErrorvalue + '|' + err.message;
                    vmorder.vPaymentInfo.resetLoadWaiting();
                    return;
                }
                // Add the nonce to the form and submit
                if (payload.liabilityShiftPossible && payload.liabilityShifted) {
                    document.querySelector('#CardNonce').value = payload.nonce;
                    submitForm = true;
                    document.querySelector('.payment-info-next-step-button').removeEventListener("click", hostedFields, false);
                    document.querySelector('.payment-info-next-step-button').click();
                }
            });
        }

        document.querySelector('input.payment-info-next-step-button').addEventListener('click', function (data) {                
                document.querySelector('#braintree-errors').innerHTML = '';
                if (!submitForm) {
                    vmorder.Checkout.setLoadWaiting('payment-info');
                    if (!stepBack) {
                        components.hostedFields.tokenize(function (err, payload) {
                            if (err) {
                                var currentErrorvalue = document.querySelector('#@Html.IdFor(model => model.Errors)').value;
                                document.querySelector('#@Html.IdFor(model => model.Errors)').value = currentErrorvalue + '|' + err.message;
                                document.querySelector('#braintree-errors').innerHTML = err.message;
                                vmorder.vPaymentInfo.resetLoadWaiting();
                                return;
                            }
                            verifyCard(payload);
                        });
                    }
                    return false;
                }
                else {
                    submitForm = false;
                    vmorder.validPayment = true;
                    vmorder.vPaymentInfo.save();
                }
            });

        function hostedFields() {
            event.preventDefault();
            document.querySelector('#braintree-errors').innerHTML = '';
            if (!submitForm) {
                if (!stepBack) {
                    components.hostedFields.tokenize(function (err, payload) {
                        if (err) {
                            var currentErrorvalue = document.querySelector('#@Html.IdFor(model => model.Errors)').value;
                            document.querySelector('#@Html.IdFor(model => model.Errors)').value = currentErrorvalue + '|' + err.message;
                            document.querySelector('#braintree-errors').innerHTML = err.message;
                            vmorder.vPaymentInfo.resetLoadWaiting();
                            return;
                        }
                        verifyCard(payload);
                    });
                }
                return false;
            }
            else {
                submitForm = false;
                PaymentInfo.save();
            }
        }
    </script>
</div>